import axios, { AxiosError } from 'axios'
import storage from './storage'
import env from '@/config'
// 创建实例
const instance = axios.create({
  timeout: 8000,
  timeoutErrorMessage: '请求超时，请稍后再试',
  withCredentials: true,
  headers: {
    icode: ''
  }
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = storage.get('token')
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    // if (env.mock) {
    //   config.baseURL = env.mockApi
    // } else {
    //   config.baseURL = env.baseApi
    // }
    return {
      ...config
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    const data = response.data
    if (response.config.responseType === 'blob') return response
    // if (data.code === 500001) {
    //   message.error(data.msg)
    //   storage.remove('token')
    //   location.href = '/login?callback=' + encodeURIComponent(location.href)
    // } else if (data.code != 0) {
    //   if (response.config.showError === false) {
    //     return Promise.resolve(data)
    //   } else {
    //     message.error(data.msg)
    //     return Promise.reject(data)
    //   }
    // }
    return data
  },
  error => {
    // message.error(error.message)
    return Promise.reject(error.message)
  }
)


export default {
  get<T>(url: string, params?: object): Promise<T> {
    return instance.get(url, { params})
  },
  post<T>(url: string, params: object,options:object ): Promise<T> {
    return instance.post(url, params,options)
  },
  downloadFile(url: string, data: any, fileName = 'fileName.xlsx') {
    instance({
      url,
      data,
      method: 'post',
      responseType: 'blob'
    }).then(response => {
      const blob = new Blob([response.data], {
        type: response.data.type
      })
      const name = (response.headers['file-name'] as string) || fileName
      const link = document.createElement('a')
      link.download = decodeURIComponent(name)
      link.href = URL.createObjectURL(blob)
      document.body.append(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(link.href)
    })
  }
}
